﻿namespace BM.Tools.WebControls.MForm.Design.PropertiesGeneration
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;

    using BM.Tools.WebControls.MForm.Controls;
    using BM.Tools.WebControls.MForm.Controls.Items;

    /// <summary>
    /// This class is used to get all the single instance templates from the given root control.
    /// </summary>
    internal class RootPropertiesObtainer
    {
        private Collection<PropertyDefinition> properties;

        /// <summary>
        /// Initializes a new instance of the <see cref="RootPropertiesObtainer"/> class.
        /// </summary>
        /// <param name="root">
        /// The MForm root control.
        /// </param>
        public RootPropertiesObtainer(Root root)
        {
            Root = root;            
        }

        /// <summary>
        /// Gets the MForm root control.
        /// </summary>
        public Root Root
        {
            get; 
            private set;
        }

        /// <summary>
        /// Gets the single instance template property definitions.
        /// </summary>
        public Collection<PropertyDefinition> Properties
        {
            get
            {
                properties = new Collection<PropertyDefinition>();
                AddProperties(Root, new List<string>());
                return properties;
            }
        }

        private void AddProperties(OffspringsOwner offspringsOwner, IEnumerable<string> pathParts)
        {
            var item = offspringsOwner.Items[0] as OffspringsOwnerItem;
            foreach (var offspring in item.Offsprings)
            {
                if (offspring.MaxOccurs != 1)
                {
                    continue;
                }

                var parts = new List<string>(pathParts)
                            {
                                    offspring.Name
                            };

                AddProperty(offspring, parts);

                var owner = offspring as OffspringsOwner;
                if (owner != null)
                {
                    AddProperties(owner, parts);
                }
            }
        }

        private void AddProperty(Offspring offspring, List<string> pathParts)
        {
            properties.Add(new PropertyDefinition
                               {                                   
                                   Name = GetPropertyName(offspring),
                                   ObjectType = offspring.Items[0].GetType(),
                                   Path = string.Join("/", pathParts.ToArray())
                               }); 
        }

        private string GetPropertyName(Offspring offspring)
        {
            return offspring.LocalName;            
        }
    }
}
